package main

import (
	"fmt"
	"sync"
	"time"
)

var rwmutex sync.RWMutex
var wg sync.WaitGroup

/*
	rwmutex 两套锁： 一套是普通锁，一套是读锁
					普通锁 是互斥的
					读锁在读goroutine之间是共享的
*/

var beginnum int //共享的全局变量
func writer(num int) {
	for {
		rwmutex.Lock()
		beginnum++
		time.Sleep(time.Millisecond * 10)
		fmt.Printf("I am [%d] writer, beginnum = %d\n", num, beginnum)
		rwmutex.Unlock()

	}
	wg.Done()
}

func reader(num int) {
	for {
		rwmutex.RLock() //加读锁
		time.Sleep(time.Millisecond * 20)
		fmt.Printf("I am [%d] reader, beginnum = %d\n", num, beginnum)
		rwmutex.RUnlock() //释放读锁
	}
	wg.Done()
}

func main() {
	wg.Add(10)
	//读写s锁适合读多写少的场景
	for i := 0; i < 3; i++ {
		go writer(i)
	}
	for i := 0; i < 7; i++ {
		go reader(i)
	}
	wg.Wait()
}
